package com.cloudlead.common.worker.web;

import com.cloudlead.common.lang.api.ActionResponse.Level;
import com.cloudlead.common.lang.api.ErrorMeta;
import com.cloudlead.common.lang.api.SimpleActionResponse;
import com.cloudlead.common.lang.utils.ExceptionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 */
@Provider
public class WebApplicationExceptionMapper implements
        ExceptionMapper<WebApplicationException> {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(WebApplicationExceptionMapper.class);

    @Override
    public Response toResponse(WebApplicationException ex) {
        LOGGER.error("invoke rest error", ex);

        ErrorMeta errorLog = ExceptionHelper.toActionError(ex);
        SimpleActionResponse<ErrorMeta> result = new SimpleActionResponse<>(
                false, Level.error, errorLog, ex.getResponse()
                .getStatusInfo().getStatusCode(), ex.getMessage());
        return Response.status(ex.getResponse().getStatusInfo())
                .entity(result).type(MediaType.APPLICATION_JSON).build();
    }

}
